﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Data.Linq.Mapping;
using System.Data.Linq;

namespace Fatec.ControleEstoque.Data.Model
{
    public partial class EstoqueEntities
    {
        #region SavingChanges
        partial void OnContextCreated()
        {
            this.SavingChanges += new EventHandler(EstoqueEntities_SavingChanges);
        }

        /// <summary>
        /// Customizando a validação antes de salvar. Cada entidade deve implementar o método Validate() de IValidatable
        /// caso queira passar por alguma validação antes de salvar.
        /// </summary>
        void EstoqueEntities_SavingChanges(object sender, EventArgs e)
        {
            EstoqueEntities entities = (EstoqueEntities)sender;

            foreach (var item in entities.ObjectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added | EntityState.Deleted )
                .Where(entry => (entry.Entity is IValidatable) && (!entry.IsRelationship))
                .Select(entry => entry.Entity as IValidatable))
            {
                if (!item.Validate(((EntityObject)item).EntityState))
                {
                    throw new ValidationException(item.ExceptionMessage);
                }
            }

        }
        #endregion


    }
}
